package com.flower.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.flower.domain.ApiResult;
import com.flower.domain.entity.BackageUser;
import com.flower.domain.entity.LoginUser;
import com.flower.service.AuthService;
import com.flower.service.BackageUserService;
import com.flower.utils.JwtUtil;
import com.flower.utils.RedisUtils;
import com.flower.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Objects;
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private RedisUtils redisUtils;
    @Resource
    private BackageUserService backageUserService;
    @Override
    public ApiResult<Map<String,Object>> login(BackageUser backageUser) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(backageUser.getName(),backageUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //authenticate 如果这个是为空的话 反映出 没有验证通过
        // 判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        //获取userid生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userid = loginUser.getBackageUser().getId().toString();
        //根据uid生成token
        String jwt = JwtUtil.createJWT(userid,24*60 * 60 * 1000L);
        Map map = new LinkedHashMap(2);
        redisUtils.set("login_id:"+userid,loginUser);
        log.warn("redis的key是:{}","login_id:"+userid);
        //修改最近登录时间
        LambdaUpdateWrapper<BackageUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(BackageUser::getId,userid);
        wrapper.set(BackageUser::getRecentLoginTime,new Date());
        backageUserService.update(wrapper);
        map.put("token",jwt);
        map.put("expried_time","24小时");
        return ApiResult.ok(map,"登录成功");
    }

    @Override
    public ApiResult<Boolean> logout() {
        Long userId = SecurityUtils.getUserId();
        log.info("取到的值是{}",userId);
        //删除redis里面的值即可
        redisUtils.del("login_id:"+userId);
        //修改登出时间
        LambdaUpdateWrapper<BackageUser> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(BackageUser::getId,userId);
        wrapper.set(BackageUser::getRecentLogoutTime,new Date());
        backageUserService.update(wrapper);
        return ApiResult.ok();
    }


}
